package org.jeecg.modules.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.chvegetable.entity.FlowerTagBook;
import org.jeecg.modules.chvegetable.service.IFlowerTagBookService;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.exception.FlowerSubTagInfoException;
import org.jeecg.modules.flower.mapper.*;
import org.jeecg.modules.flower.service.*;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flowerutil.controller.PeriodController;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 出库单主表
 * @Author: jeecg-boot
 * @Date: 2022-06-27
 * @Version: V1.0
 */
@Service
@Slf4j
public class FlowerOutorderServiceImpl extends ServiceImpl<FlowerOutorderMapper, FlowerOutorder> implements IFlowerOutorderService {

    @Autowired
    private FlowerOutorderMapper flowerOutorderMapper;
    @Autowired
    private FlowerOutorderinfoMapper flowerOutorderinfoMapper;
    @Autowired
    private FlowerStorehouseMapper flowerStorehouseMapper;
    @Autowired
    private FlowerOutorderinfoDMapper flowerOutorderinfoDMapper;
    @Autowired
    private XsglService xsglService;

    @Autowired
    private FlowerTagInfoMapper flowerTagInfoMapper;

    @Autowired
    private IFlowerTagInfoService flowerTagInfoService;
    @Autowired
    private IFlowerOutlogService flowerOutlogService;

    @Autowired
    private IFlowerTagBookService flowerTagBookService;
    @Autowired
    private IFlowerOutorderPrtService flowerOutorderPrtService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveMain(FlowerOutorder flowerOutorder, List<FlowerOutorderinfo> flowerOutorderinfoList) throws IOException {
        String rest = "";
        //自动生成出库单号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateNo = simpleDateFormat.format(new Date());
        String refex = "CH-CK-" + dateNo;
        LambdaQueryWrapper<FlowerOutorder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(FlowerOutorder::getOrderNo, refex);
        lambdaQueryWrapper.orderByDesc(FlowerOutorder::getOrderNo);
        List<FlowerOutorder> list = this.list(lambdaQueryWrapper);
        String oldNo = "";
        if (list.size() > 0) {
            oldNo = list.get(0).getOrderNo();
        }
        String no1 = CommonUtil.getNo("CH-CK-", oldNo, 3);
        flowerOutorder.setOrderNo(no1);//自动生成出库单号
        if (StringUtils.isBlank(flowerOutorder.getPeriod())) {
            PeriodController periodController = new PeriodController();
            String currentPeriod = periodController.getCurrentPeriod();
            flowerOutorder.setPeriod(currentPeriod);
        }
        flowerOutorder.setState(-1);
        if (flowerOutorder.getOrderType() == null) {
            flowerOutorder.setOrderType(0);
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        //自动生成出库单号========end====
        String source = flowerOutorder.getSource();
        String userid = flowerOutorder.getUserid();
        if (StringUtils.isBlank(source)) {
            //来源为空时设置默认为“销售系统”
            flowerOutorder.setSource("手动出库");
        } else {
//            if("销售系统".equals(source) || "补货".equals(source)) {
//                flowerOutorder.setState(1); //跳过基地负责人审核
//            }
        }
        if (StringUtils.isBlank(userid)) {
            throw new RuntimeException("客户id为空，请重新选择客户信息！");
        }
        BigDecimal sumNumber =  new BigDecimal("0");
        BigDecimal sumMoney = new BigDecimal("0");
        for (FlowerOutorderinfo flowerOutorderinfo : flowerOutorderinfoList) {
            BigDecimal number = flowerOutorderinfo.getNumber();
            sumNumber = sumNumber.add(number) ;
            sumMoney = sumMoney.add(flowerOutorderinfo.getTotalprice());
        }
        flowerOutorder.setNumber(sumNumber);
        flowerOutorder.setTotalprice(sumMoney);
        flowerOutorder.setState(-1);
        flowerOutorderMapper.insert(flowerOutorder);

        if (flowerOutorderinfoList != null && flowerOutorderinfoList.size() > 0) {
            QueryWrapper<FlowerStorehouse> queryWrapperHouse = new QueryWrapper();
            List<FlowerStorehouse> flowerStorehouses = flowerStorehouseMapper.selectList(queryWrapperHouse);
            Map<String, String> houseMaps = new HashMap<>();
            for (FlowerStorehouse flowerStorehouse : flowerStorehouses) {
                houseMaps.put(flowerStorehouse.getCode(), flowerStorehouse.getCost());
            }

            for (FlowerOutorderinfo entity : flowerOutorderinfoList) {
                String sourceBase = entity.getSourceBase();
                String sourceGreenhouse = entity.getSourceGreenhouse();
                String varietyCode = entity.getVarietyCode();
                String storehouse = entity.getStorehouse();
                String packingSpecifications = entity.getPackingSpecifications();
                String flowerPoleLength = entity.getFlowerPoleLength();
                String cost2 = entity.getCost();

                //2022年11月2日13:28:22加入是否库存足够的判断
                if (!"销售系统".equals(source) && !"补货".equals(source)) {
                    QueryWrapper<FlowerTagInfo> taginfoQuery = new QueryWrapper<>();
                    taginfoQuery.select("count(1) as tag_num");
                    taginfoQuery.eq("source_base", sourceBase);
                    taginfoQuery.eq("source_greenhouse", sourceGreenhouse);
                    taginfoQuery.eq("variety_code", varietyCode);
                    taginfoQuery.eq("storehouse", storehouse);
                    taginfoQuery.eq("packing_specifications", packingSpecifications);
                    taginfoQuery.eq("flower_pole_length", flowerPoleLength);
                    taginfoQuery.eq("state", 1);//已入库的台账
                    taginfoQuery.orderByAsc("sort_time");
                    FlowerTagInfo tagInfo = flowerTagInfoMapper.selectOne(taginfoQuery);
                    BigDecimal number = tagInfo.getTagNum();
                    if (number == null || number.compareTo( entity.getNumber())<0) {
                        throw new RuntimeException(entity.getVariety() + "(" + varietyCode + ")库存不够（剩余库存" + number + ",需要" + entity.getNumber() + "），请重新填写数量");
                    }
                } else {
                    QueryWrapper<FlowerTagInfo> taginfoQuery = new QueryWrapper<>();
                    taginfoQuery.eq("cost", cost2);
                    taginfoQuery.eq("variety_code", varietyCode);
                    taginfoQuery.eq("packing_specifications", packingSpecifications);
                    taginfoQuery.eq("flower_pole_length", flowerPoleLength);
                    taginfoQuery.eq("state", 1);//已入库的台账
                    taginfoQuery.orderByAsc("sort_time");
                    BigDecimal number = new BigDecimal(flowerTagInfoMapper.selectCount(taginfoQuery));
                    BigDecimal number2 = number;
                    if (number2 == null || number2.compareTo(entity.getNumber()) < 0) {
                        throw new RuntimeException(entity.getVariety() + "(" + varietyCode + ")库存不够（剩余库存" + number + ",需要" + entity.getNumber() + "），请重新填写数量");
                    }
                }
                //2022年11月2日13:28:22加入是否库存足够的判断--end--

                //外键设置
                entity.setOrderId(flowerOutorder.getId());
                //如果成本中心为空，就自动根据仓库去查找成本中心，并插入数据。
                if (StringUtils.isNotBlank(storehouse)) {
                    entity.setCost(houseMaps.get(storehouse));
                }
                flowerOutorderinfoMapper.insert(entity);
            }
        }
        return rest;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(FlowerOutorder flowerOutorder, List<FlowerOutorderinfo> flowerOutorderinfoList) {
        if (flowerOutorder.getState() != -1) {
            throw new RuntimeException("待出库状态才能修改！");
        }
        String userid = flowerOutorder.getUserid();
        if (StringUtils.isBlank(userid)) {
            throw new RuntimeException("客户id为空，请重新选择客户信息！");
        }
        flowerOutorderMapper.updateById(flowerOutorder);
        List<FlowerOutorderinfo> flowerOutorderinfoListOld = flowerOutorderinfoMapper.selectByMainId(flowerOutorder.getId());
        //1.先删除子表数据
        flowerOutorderinfoMapper.deleteByMainId(flowerOutorder.getId());

        //****注意****修改时子表的id一定不能变
        //****注意****修改时子表的id一定不能变
        //****注意****修改时子表的id一定不能变
        //****注意****修改时子表的id一定不能变
        List<FlowerOutorderinfoD> flowerOutorderinfoDS = new ArrayList<>();
        //1.1 先删除子表 的子表 数据
        for (FlowerOutorderinfo entity : flowerOutorderinfoListOld) {
            QueryWrapper<FlowerOutorderinfoD> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("mainid", entity.getId());
            List<FlowerOutorderinfoD> flowerOutorderinfoDS2 = flowerOutorderinfoDMapper.selectList(queryWrapper);
            flowerOutorderinfoDMapper.delete(queryWrapper);
            flowerOutorderinfoDS2.forEach((i) -> {
                flowerOutorderinfoDS.add(i);
            });
        }

        String source = flowerOutorder.getSource();
        //2.子表数据重新插入
        if (flowerOutorderinfoList != null && flowerOutorderinfoList.size() > 0) {
            QueryWrapper<FlowerStorehouse> queryWrapperHouse = new QueryWrapper();
            List<FlowerStorehouse> flowerStorehouses = flowerStorehouseMapper.selectList(queryWrapperHouse);
            Map<String, String> houseMaps = new HashMap<>();
            for (FlowerStorehouse flowerStorehouse : flowerStorehouses) {
                houseMaps.put(flowerStorehouse.getCode(), flowerStorehouse.getCost());
            }

            for (FlowerOutorderinfo entity : flowerOutorderinfoList) {
                //2022年11月2日13:28:22加入是否库存足够的判断
                String sourceBase = entity.getSourceBase();
                String sourceGreenhouse = entity.getSourceGreenhouse();
                String varietyCode = entity.getVarietyCode();
                String storehouse = entity.getStorehouse();
                String packingSpecifications = entity.getPackingSpecifications();
                String flowerPoleLength = entity.getFlowerPoleLength();
                String cost2 = entity.getCost();

                if (!"销售系统".equals(source) && !"补货".equals(source)) {
                    QueryWrapper<FlowerTagInfo> taginfoQuery = new QueryWrapper<>();
                    taginfoQuery.select("count(1) as tag_num");
                    taginfoQuery.eq("source_base", sourceBase);
                    taginfoQuery.eq("source_greenhouse", sourceGreenhouse);
                    taginfoQuery.eq("variety_code", varietyCode);
                    taginfoQuery.eq("storehouse", storehouse);
                    taginfoQuery.eq("packing_specifications", packingSpecifications);
                    taginfoQuery.eq("flower_pole_length", flowerPoleLength);
                    taginfoQuery.eq("state", 1);//已入库的台账
                    taginfoQuery.orderByAsc("sort_time");
                    FlowerTagInfo tagInfo = flowerTagInfoMapper.selectOne(taginfoQuery);

                    BigDecimal number = tagInfo.getTagNum();
                    if (number == null || number.compareTo( entity.getNumber()) <0) {
                        throw new RuntimeException(entity.getVariety() + "(" + varietyCode + ")库存不够（剩余库存" + number + ",需要" + entity.getNumber() + "），请重新填写数量");
                    }
                } else {
                    QueryWrapper<FlowerTagInfo> taginfoQuery = new QueryWrapper<>();
                    taginfoQuery.eq("cost", cost2);
                    taginfoQuery.eq("variety_code", varietyCode);
                    taginfoQuery.eq("packing_specifications", packingSpecifications);
                    taginfoQuery.eq("flower_pole_length", flowerPoleLength);
                    taginfoQuery.eq("state", 1);//已入库的台账
                    taginfoQuery.orderByAsc("sort_time");
                    Long number = flowerTagInfoMapper.selectCount(taginfoQuery);
                    BigDecimal number2 =new BigDecimal(number.toString());
//                    Integer number = Math.toIntExact(flowerTagInfoMapper.selectCount(taginfoQuery));
                    if (number2 == null || number2 .compareTo(entity.getNumber())< 0) {
                        throw new RuntimeException(entity.getVariety() + "(" + varietyCode + ")库存不够（剩余库存" + number + ",需要" + entity.getNumber() + "），请重新填写数量");
                    }
                }

                //如果成本中心为空，就自动根据仓库去查找成本中心，并插入数据。
                String cost = entity.getCost();
                if (StringUtils.isNotBlank(storehouse)) {
                    entity.setCost(houseMaps.get(storehouse));
                }
                //外键设置
                entity.setOrderId(flowerOutorder.getId());
                flowerOutorderinfoMapper.insert(entity);

                String mainid = entity.getId();
                //3.插入新的 子表 的子表 数据
                flowerOutorderinfoDS.forEach(flowerOutorderinfoD -> {
                    if (mainid.equals(flowerOutorderinfoD.getMainid())) {
                        flowerOutorderinfoDMapper.insert(flowerOutorderinfoD);
                    }
                });
            }
        }
    }

    @Override
    public void updateFlowerOutorderinfo(List<FlowerOutorderinfo> flowerOutorderinfoList) {
        for (FlowerOutorderinfo flowerOutorderinfo : flowerOutorderinfoList) {
            FlowerOutorderinfo newFlowerOutorderinfo = new FlowerOutorderinfo();
            newFlowerOutorderinfo.setId(flowerOutorderinfo.getId());
            newFlowerOutorderinfo.setPrice(flowerOutorderinfo.getPrice());
            newFlowerOutorderinfo.setTotalprice(flowerOutorderinfo.getTotalprice());
            flowerOutorderinfoMapper.updateById(newFlowerOutorderinfo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        FlowerOutorder byId = this.getById(id);
        if (byId.getState() != -1) {
            throw new RuntimeException("待出库状态才能删除！");
        }
        //3.先删除子表 的子表 数据
        QueryWrapper<FlowerOutorderinfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("order_id", id);
        List<FlowerOutorderinfo> flowerOutorderinfoList = flowerOutorderinfoMapper.selectList(queryWrapper2);
        for (FlowerOutorderinfo flowerOutorderinfo : flowerOutorderinfoList) {
            QueryWrapper<FlowerOutorderinfoD> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("mainid", flowerOutorderinfo.getId());
            flowerOutorderinfoDMapper.delete(queryWrapper);
        }
        byId.setState(-2);
        flowerOutorderMapper.updateById(byId);
//        flowerOutorderinfoMapper.deleteByMainId(id);
//        flowerOutorderMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            FlowerOutorder byId = this.getById(id);
            if (byId.getState() != -1) {
                throw new RuntimeException("待出库状态才能删除！");
            }
            //3.先删除子表 的子表 数据
            QueryWrapper<FlowerOutorderinfo> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("order_id", id);
            List<FlowerOutorderinfo> flowerOutorderinfoList = flowerOutorderinfoMapper.selectList(queryWrapper2);
            for (FlowerOutorderinfo flowerOutorderinfo : flowerOutorderinfoList) {
                QueryWrapper<FlowerOutorderinfoD> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("mainid", flowerOutorderinfo.getId());
                flowerOutorderinfoDMapper.delete(queryWrapper);
            }
            byId.setState(-2);
            flowerOutorderMapper.updateById(byId);
//            flowerOutorderinfoMapper.deleteByMainId(id.toString());
//            flowerOutorderMapper.deleteById(id);
        }
    }

    @Override
    public List<FlowerTagInfo> getTaginfoByOutoerderID(String id) {
        return baseMapper.getTaginfoByOutoerderID(id);
    }

    @Override
    public IPage<FlowerTagInfo> getFlowerVarietys(IPage<FlowerTagInfo> page, Wrapper<FlowerTagInfo> wrapper) {
        return baseMapper.getFlowerVarietys(page, wrapper);
    }

    @Override
    public IPage<FlowerTagInfo> getFlowerVarietys2(IPage<FlowerTagInfo> page, Wrapper<FlowerTagInfo> wrapper) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        return baseMapper.getFlowerVarietys2(page, wrapper, sysUser.getId());
    }


    /**
     * kuguan qkuguan 库管确认
     *
     * @return int
     * @descriptionauthor
     * @author gf
     * 2022-11-23 13:27
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int sureOutDo(String id) throws IOException {
        int rest = 0;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        FlowerOutorder outOrder = this.getById(id);
        if (outOrder.getState() == 0) {
            throw new FlowerSubTagInfoException("您已经成功出库过了");
        }
        if (outOrder.getState() != 2) {
            throw new FlowerSubTagInfoException("请先进行【运管备案】");
        }
        //修改主表状态
        FlowerOutorder flowerOutorder = new FlowerOutorder();
        flowerOutorder.setId(id);
        flowerOutorder.setState(0);

        flowerOutorder.setFinaSureTime(outOrder.getFinaSureTime());//基地负责人
        flowerOutorder.setSurepipetime(outOrder.getSurepipetime());//运管备案
        flowerOutorder.setSureoutuser(sysUser.getRealname());//确认出库
        flowerOutorder.setSureouttime(new Date());
        flowerOutorder.setTopresstime(outOrder.getTopresstime() );
        this.updateById(flowerOutorder);



        //预出库扣减库存 --总台账
        Map<String, String> houseNames = CommonUtil.getHouseNames();
        Map<String, String> greenHouseNames = CommonUtil.getGreenHouseNames();
        String wrangContent = "";
        int showNum = 1;
        List<FlowerTagBook> lowBookListPre = flowerTagBookService.getLowBookList( id );
        for (FlowerTagBook flowerTagBook : lowBookListPre) {
            wrangContent = wrangContent + "  " + showNum + "、提示：" + greenHouseNames.get(flowerTagBook.getSourceGreenhouse()) + houseNames.get(flowerTagBook.getStorehouse()) + " " + flowerTagBook.getVariety() + flowerTagBook.getVarietyCode() + "，长度：" + flowerTagBook.getFlowerPoleLength() + "-数量不足"+flowerTagBook.getTotalNumber()+",还差" + (flowerTagBook.getNumber()) + " ；";
            showNum++;
        }
        if (StringUtils.isNotBlank(wrangContent)) {
            throw new RuntimeException(wrangContent);
        }
        flowerTagBookService.subBookInfoFromOutOrder(id);
        Integer integer = flowerTagBookService.checkBooksIsErr();
        if(integer>0){
            throw new RuntimeException("库存数据有误，请联系管理员"+outOrder.getOrderNo());
        }

        return rest;
    }

    /**
     * kuguan qkuguan 库管确认
     *
     * @return int
     * @descriptionauthor
     * @author gf
     * 2022-11-23 13:27
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int sureOutDoBack(String id) throws IOException {
        int rest = 0;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        FlowerOutorder byId = this.getById(id);
        if(byId==null || byId.getState()!=0){
            throw new RuntimeException("请先确认出库后才能撤销");
        }
        //1、修改主表状态
        FlowerOutorder flowerOutorder = new FlowerOutorder();
        flowerOutorder.setId(id);
        flowerOutorder.setState(2); //状态
        flowerOutorder.setTopresstime(byId.getTopresstime() );
        flowerOutorder.setFinaSureTime( byId.getFinaSureTime());
        flowerOutorder.setSurepipetime( byId.getSurepipetime());
        flowerOutorder.setSureoutuser("");
        flowerOutorder.setSureouttime( null);
        this.updateById(flowerOutorder);

        flowerTagBookService.subBookInfoFromOutOrderBack(id);
        Integer integer = flowerTagBookService.checkBooksIsErr();
        if(integer>0){
            throw new RuntimeException("库存数据有误，请联系管理员"+byId.getOrderNo());
        }
        try {
            final String orderNo = byId.getOrderNo();
            QueryWrapper<FlowerOutorderPrt> flowerOutorderPrtQueryWrapper = new QueryWrapper<>();
            flowerOutorderPrtQueryWrapper.eq("order_no", orderNo);
            boolean remove = flowerOutorderPrtService.remove(flowerOutorderPrtQueryWrapper);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return rest;
    }

    /**
     * @return java.lang.String
     * @descriptionauthor 基地负责人审核
     * @author gf
     * 2022-11-23 17:53
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String fiunalSure(@RequestParam(value = "id") String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        String rest = "";
        FlowerOutorder flowerOutorderOld = this.getById(id);
        if (flowerOutorderOld.getState() == 1) {
            throw new RuntimeException("您已经 基地负责人审核 过了");
        }
        if (flowerOutorderOld.getState().compareTo(3) != 0) {
            throw new RuntimeException("只有【提交审核】状态才能进行基地负责人审核");
        }

        FlowerOutorder flowerOutorder = new FlowerOutorder();
        flowerOutorder.setId(id);
        flowerOutorder.setFinaSureUser(sysUser.getRealname());
        flowerOutorder.setFinaSureTime(new Date());
        flowerOutorder.setState(1); //1基地负责人审核
        flowerOutorder.setTopresstime(flowerOutorderOld.getTopresstime());
        boolean b = this.updateById(flowerOutorder);
        if (b) {
            rest = ("基地负责人审核成功");
        } else {
            rest = ("基地负责人审核失败");
        }
        return rest;
    }

    /**
     * 运管备案
     *
     * @return
     * @descriptionauthor
     * @author gf
     * 2022-9-27 16:31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer transportPipe(String id, String remarks, BigDecimal sumNum, BigDecimal sumTotalprice) throws IOException {
        LoginUser sysUser = null;
        try {
            sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        } catch (Exception e) {
            sysUser = new LoginUser();
            sysUser = sysUser.setRealname("自动确认");
            sysUser = sysUser.setUsername("自动确认");
        }
        FlowerOutorder flowerOutorderOld = this.getById(id);
        if (flowerOutorderOld.getState() == 2) {
            throw new RuntimeException("您已经 运管备案过了");
        }
        if (flowerOutorderOld.getState() != 1) {
            throw new RuntimeException("只有【基地负责人】审批后才能进行运管备案");
        }
        String source = flowerOutorderOld.getSource();
//        if ("销售系统".equals(source) || "补货".equals(source)) {
//            throw new RuntimeException("销售系统出库单不可运管确认！");
//        }
        FlowerOutorder flowerOutorder = new FlowerOutorder();
        flowerOutorder.setId(id);
        flowerOutorder.setState(2);
        if (StringUtils.isNotBlank(remarks)) {
            flowerOutorder.setRemarks(remarks);
        }
        //更新主表数量和 总价
        if (sumNum != null) {
            flowerOutorder.setNumber(sumNum);
        }
        if (sumTotalprice != null) {
            flowerOutorder.setTotalprice(sumTotalprice);
        }
        flowerOutorder.setFinaSureTime(flowerOutorderOld.getFinaSureTime());
        flowerOutorder.setSureouttime(flowerOutorderOld.getSureouttime());
        flowerOutorder.setSurepipeuser(sysUser.getRealname());
        flowerOutorder.setSurepipetime(new Date());
        flowerOutorder.setTopresstime(flowerOutorderOld.getTopresstime());

        boolean b = this.updateById(flowerOutorder);
        return null;
    }

    /**
     * 运管备案  -撤销
     *
     * @return java.lang.Integer
     * @descriptionauthor
     * @author gf
     * 2022-12-27 14:58
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer transportPipeBack(String id) throws IOException {
        FlowerOutorder flowerOutorderOld = this.getById(id);
        Integer state = flowerOutorderOld.getState();
        if (state != 2) {
            throw new RuntimeException("还未进行运管备案，不可取消！");
        }

        FlowerOutorder flowerOutorder = new FlowerOutorder();
        flowerOutorder.setId(id);
        flowerOutorder.setState(1); //退回到 基地负责人审核
        flowerOutorder.setSurepipeuser("");
        flowerOutorder.setSurepipetime(null);
        flowerOutorder.setFinaSureTime(flowerOutorderOld.getFinaSureTime());
        flowerOutorder.setSureouttime(flowerOutorderOld.getSureouttime());
        flowerOutorder.setTopresstime(flowerOutorderOld.getTopresstime());

        boolean b = this.updateById(flowerOutorder);

        return null;
    }

    /**
     * @return java.lang.Integer
     * @descriptionauthor 提交审核----扣减库存改到此处
     * @author gf
     * 2023-1-3 12:29
     * [id] 状态（-1草稿，0库管已确认出库，1基地负责人审核，2运管备案，3待审核）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer toPress(String id) throws IOException {
        int rest = 0;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        FlowerOutorder outOrder = this.getById(id);
        if (outOrder.getState() == 3) {
            throw new FlowerSubTagInfoException("您已经成功提交过了");
        }
        if (outOrder.getState().compareTo(-1) != 0) {
            throw new FlowerSubTagInfoException("【草稿】状态才能进行【提交审核】");
        }
        //修改主表状态
        FlowerOutorder flowerOutorder = new FlowerOutorder();
        flowerOutorder.setId(id);
        flowerOutorder.setState(3);
        flowerOutorder.setTopresstime(new Date());
        String source = outOrder.getSource();
//        flowerOutorder.setFinaSureTime( outOrder.getFinaSureTime() );//基地负责人
//        flowerOutorder.setSurepipetime( outOrder.getSurepipetime() );//运管备案
//        flowerOutorder.setSureoutuser(sysUser.getRealname());//确认出库
//        flowerOutorder.setSureouttime(new Date());

        QueryWrapper<FlowerOutorderinfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("sum(  replace(convert(packing_specifications using ascii),'?','')  * number   ) as number");
        queryWrapper.select("sum(  number   ) as number, sum(totalprice) as totalprice");
        queryWrapper.eq("order_id", id);
        FlowerOutorderinfo flowerOutorderinfoServiceOne = flowerOutorderinfoMapper.selectOne(queryWrapper);
        flowerOutorder.setNumber(flowerOutorderinfoServiceOne.getNumber());
        flowerOutorder.setTotalprice(flowerOutorderinfoServiceOne.getTotalprice());
        // 判断余额
        if(CommonUtil.isLinkSealSystem()) {
            BigDecimal userMoney = xsglService.getXSGLUserMoney(outOrder.getUserid());
            if (flowerOutorderinfoServiceOne.getTotalprice().compareTo(userMoney) > 0) {
                throw new FlowerSubTagInfoException(outOrder.getUser() + "的余额只有：" + userMoney + "不够出库单金额：" + flowerOutorderinfoServiceOne.getTotalprice() + "！请先在销售系统中充值！");
            }
        }
        //子表列表
        LambdaQueryWrapper<FlowerOutorderinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FlowerOutorderinfo::getOrderId, id);
        List<FlowerOutorderinfo> flowerOutorderinfoList = flowerOutorderinfoMapper.selectList(lambdaQueryWrapper);
        if (flowerOutorderinfoList.size() == 0) {
            throw new FlowerSubTagInfoException("请先新增出库品种！");
        }


        //预出库扣减库存 --总台账
        Map<String, String> houseNames = CommonUtil.getHouseNames();
        Map<String, String> greenHouseNames = CommonUtil.getGreenHouseNames();
        String wrangContent = "";
        int showNum = 1;
        List<FlowerTagBook> lowBookListPre = flowerTagBookService.getLowBookList( id );
        for (FlowerTagBook flowerTagBook : lowBookListPre) {
            wrangContent = wrangContent + "  " + showNum + "、提示：" + greenHouseNames.get(flowerTagBook.getSourceGreenhouse()) + houseNames.get(flowerTagBook.getStorehouse()) + " " + flowerTagBook.getVariety() + flowerTagBook.getVarietyCode() + "，长度：" + flowerTagBook.getFlowerPoleLength() + "-数量不足"+flowerTagBook.getTotalNumber()+",还差" + (flowerTagBook.getNumber()) + " ；";
            showNum++;
        }
        if (StringUtils.isNotBlank(wrangContent)) {
            throw new RuntimeException(wrangContent);
        }
        flowerTagBookService.lockTagnumfroOut(id);
        Integer integer = flowerTagBookService.checkBooksIsErr();
        if(integer>0){
            throw new RuntimeException("库存数据有误，请联系管理员"+outOrder.getOrderNo());
        }


        this.updateById(flowerOutorder);

        //调用销售系统订单确认出库的接口--发短信
        try {
            String userid = outOrder.getUserid();
            String outNo = outOrder.getOrderNo();
            xsglService.orderConfirmOutStock(userid, outNo);

            //发出库成功通知
            if ("销售系统".equals(source) || "补货".equals(source)) {
                //通知销售已经出库
                try {
                    xsglService.senOutNotice(outOrder.getSealNo());
                }catch (Exception e) {
                    log.error("推送给销售系统的  出库通知  失败：" + outOrder.getSealNo());
                }
            }
        } catch (Exception e) {
            log.error("调用销售系统订单发送收货码失败！");
        }
        return rest;
    }

    //提交审核----撤销
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer toPressBack(String id) throws IOException {
        FlowerOutorder outOrder = this.getById(id);
        if (outOrder == null || outOrder.getState().compareTo(3) != 0) {
            throw new RuntimeException("请先【提交审核】后才能撤销");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        //1、修改主表状态
        FlowerOutorder flowerOutorder = new FlowerOutorder();
        flowerOutorder.setId(id);
        flowerOutorder.setState(-1); //状态
        flowerOutorder.setFinaSureTime(outOrder.getFinaSureTime());
        flowerOutorder.setSurepipetime(outOrder.getSurepipetime());
        flowerOutorder.setTopresstime(null);
        this.updateById(flowerOutorder);


        // 修改总台账数据
        flowerTagBookService.lockTagnumfroOutBack(id);
        Integer integer = flowerTagBookService.checkBooksIsErr();
        if(integer>0){
            throw new RuntimeException("库存数据有误，请联系管理员"+outOrder.getOrderNo());
        }

        return integer;
    }


    /**
     *
     * @descriptionauthor结算确认
     * @author gf
     * 2023-2-6 9:20
     * [flowerOutorder]
     * @return java.lang.Integer
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer accountSure(FlowerOutorder flowerOutorder) throws IOException {
        LoginUser sysUser =  (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        String id = flowerOutorder.getId();
        FlowerOutorder flowerOutorderNew = new FlowerOutorder();
        flowerOutorderNew.setId(id);
        flowerOutorderNew.setState(4);

        flowerOutorderNew.setTopresstime(flowerOutorder.getTopresstime());
        flowerOutorderNew.setFinaSureTime(flowerOutorder.getFinaSureTime());
        flowerOutorderNew.setSureouttime(flowerOutorder.getSureouttime());
        flowerOutorderNew.setSurepipetime( flowerOutorder.getSurepipetime());
        flowerOutorderNew.setAccounter(sysUser.getRealname());
        flowerOutorderNew.setAccounttime(new Date());

        if(CommonUtil.isLinkSealSystem()) {
            BigDecimal outAmount = flowerOutorder.getTotalprice();
            String userid = flowerOutorder.getUserid();
            BigDecimal subtract = BigDecimal.ZERO.subtract(outAmount);
            Date stockInTime = flowerOutorder.getStockInTime();
            String orderNo = flowerOutorder.getOrderNo();
            String isinvoice = flowerOutorder.getIsinvoice();
            String businessPerson = flowerOutorder.getBusinessPerson();
            String outType = "0";//出库类型（0：先款后货,既正常出库，1：先货后款,既预出库）

            BigDecimal userMoney = xsglService.getXSGLUserMoney(userid);
            if (outAmount.compareTo(userMoney) > 0) {
                throw new FlowerSubTagInfoException(flowerOutorder.getUser() + "的余额只有：" + userMoney + "不够出库单金额：" + outAmount + "！请先在销售系统中充值！");
            }
            Xsgl xsgl = new Xsgl();
            xsgl.setUserId(userid);
            xsgl.setOutNo(orderNo);
            xsgl.setOutAmount(null);
            xsgl.setSettAmount(outAmount);
            xsgl.setOutTime(null);
            xsgl.setSettTime(new Date());
            xsgl.setBusinessPersion(businessPerson);
            xsgl.setIsInvoice(isinvoice);
            xsgl.setOutType(outType);
            xsgl.setSealNo(null);
            Integer integer = xsglService.sendOrderInfo(xsgl);
        }

        boolean b = this.updateById(flowerOutorderNew);
        return 0;
    }
//    结算确认-撤销
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer accountSureBack(String id) throws IOException {

        FlowerOutorder flowerOutorder = this.getById( id);
        FlowerOutorder flowerOutorderNew = new FlowerOutorder();
        flowerOutorderNew.setId(id);
        flowerOutorderNew.setState(0);

        flowerOutorderNew.setTopresstime(flowerOutorder.getTopresstime());
        flowerOutorderNew.setFinaSureTime(flowerOutorder.getFinaSureTime());
        flowerOutorderNew.setSureouttime(flowerOutorder.getSureouttime());
        flowerOutorderNew.setSurepipetime( flowerOutorder.getSurepipetime());
        flowerOutorderNew.setAccounter("");
        flowerOutorderNew.setAccounttime( null);

        if(CommonUtil.isLinkSealSystem()) {
            BigDecimal outAmount = flowerOutorder.getTotalprice();
            String userid = flowerOutorder.getUserid();
            BigDecimal subtract = BigDecimal.ZERO.subtract(outAmount);
            Date stockInTime = flowerOutorder.getStockInTime();
            String orderNo = flowerOutorder.getOrderNo();
            String isinvoice = flowerOutorder.getIsinvoice();
            String businessPerson = flowerOutorder.getBusinessPerson();
            String outType = "0";//出库类型（0：先款后货,既正常出库，1：先货后款,既预出库）


            Xsgl xsgl = new Xsgl();
            xsgl.setUserId(userid);
            xsgl.setOutNo(orderNo);
            xsgl.setOutAmount(null);
            xsgl.setSettAmount(subtract);
            xsgl.setOutTime(null);
            xsgl.setSettTime(new Date());
            xsgl.setBusinessPersion(businessPerson);
            xsgl.setIsInvoice(isinvoice);
            xsgl.setOutType(outType);
            xsgl.setSealNo(null);
            Integer integer = xsglService.sendOrderInfo(xsgl);
        }
        boolean b = this.updateById(flowerOutorderNew);
        return  null;
    }
}
